const API_BASE = '/api';

import React, { useState, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { useSearchParams } from 'react-router-dom';
import { translateDataField } from '../../utils/i18nDataTranslator';
import StudentModal from './components/StudentModal';
import styles from './StudentManagement.module.css';

interface Student {
  id: number;
  name: string;
  studentId: string;
  gender: string;
  birthDate: string;
  idCard: string;
  marketingDepartment: string;
  className: string;
  college: string;
  phone: string;
  dormBuilding: string;
  dormRoom: string;
  status: 'active' | 'suspended' | 'graduated';
  enrollmentDate: string;
  email?: string;
  guardianName?: string;
  guardianPhone?: string;
  guardianRelationship?: string;
}

interface Pagination {
  current: number;
  pageSize: number;
  total: number;
  totalPages: number;
}

interface StudentsResponse {
  data: Student[];
  pagination: Pagination;
}

// 导入相关接口
interface ImportResult {
  success: boolean;
  message: string;
  details: Array<{
    studentId: string;
    name: string;
    status: string;
    message: string;
  }>;
  total: number;
  successCount: number;
  failedCount: number;
}


// 学生评语相关接口
interface StudentComment {
  stage: string;
  teacher: string;
  score: number;
  comment: string;
  date: string;
}

interface StudentCommentsData {
  studentId: number;
  studentNumber: string;
  studentName: string;
  className: string;
  comments: StudentComment[];
}


const StudentManagement = () => {
  const { t } = useTranslation('student');
  const [searchParams] = useSearchParams();
  const [students, setStudents] = useState<Student[]>([]);
  // 新增：用于表头全选框的ref
  const selectAllRef = React.useRef<HTMLInputElement>(null);
  // 新增：用于选中多行状态
  const [selectedIds, setSelectedIds] = useState<number[]>([]);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingStudent, setEditingStudent] = useState<Student | null>(null);
  const [isImportModalOpen, setIsImportModalOpen] = useState(false);
  const [isCommentModalOpen, setIsCommentModalOpen] = useState(false);
  const [importResult, setImportResult] = useState<ImportResult | null>(null);
  const [isImporting, setIsImporting] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // 获取当前用户信息
  const getCurrentUser = () => {
    try {
      const userStr = localStorage.getItem('user');
      return userStr ? JSON.parse(userStr) : null;
    } catch (error) {
      console.error('获取用户信息失败:', error);
      return null;
    }
  };

  const currentUser = getCurrentUser();
  const isAdmin = currentUser?.role === 'admin';
  const [userPermissions, setUserPermissions] = useState<string[]>([]);

  // 加载当前用户的权限
  useEffect(() => {
    const loadUserPermissions = async () => {
      try {
        const token = localStorage.getItem('accessToken') || localStorage.getItem('token');
        if (!token) return;

        const response = await fetch(`${API_BASE}/permissions/me`, {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        });

        if (response.ok) {
          const result = await response.json();
          const permissionCodes = result.data?.permissionCodes || [];
          setUserPermissions(permissionCodes);
          console.log('当前用户权限:', permissionCodes);
        } else {
          console.error('获取用户权限失败:', response.status);
        }
      } catch (error) {
        console.error('加载用户权限失败:', error);
      }
    };

    loadUserPermissions();
  }, []);

  // 检查用户是否有指定权限
  const hasPermission = (permissionCode: string): boolean => {
    // 管理员自动拥有所有权限
    if (isAdmin) return true;
    return userPermissions.includes(permissionCode);
  };

  // 搜索相关状态
  const [searchFilters, setSearchFilters] = useState({
    college: '',
    className: '',
    name: '',
    idCard: '',
    phone: '',
    gender: '',
    status: '',
    dormBuilding: '',
    dormRoom: ''
  });

  const [pagination, setPagination] = useState<Pagination>({
    current: 1,
    pageSize: 10,
    total: 0,
    totalPages: 0
  });

  // 评语相关状态
  const [selectedStudent, setSelectedStudent] = useState<Student | null>(null);
  const [studentComments, setStudentComments] = useState<StudentCommentsData | null>(null);
  const [availableStages, setAvailableStages] = useState<string[]>([]);

  // 初始化学生数据
  const fetchStudents = useCallback(async (page: number = 1, pageSize: number = 10) => {
    setIsLoading(true);
    setError(null);
    try {
      const token = localStorage.getItem('accessToken') || localStorage.getItem('token');

      // 构建查询参数
      const params = new URLSearchParams({
        page: page.toString(),
        pageSize: pageSize.toString()
      });

      // 添加搜索条件
      Object.entries(searchFilters).forEach(([key, value]) => {
        if (value && value.trim()) {
          params.append(key, value.trim());
        }
      });


      const url = `${API_BASE}/students?${params.toString()}`;
      console.log('请求URL:', url); // 调试用

      const headers: Record<string, string> = {};
      if (token) {
        headers['Authorization'] = `Bearer ${token}`;
      }

      const response = await fetch(url, {
        headers
      });
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data: StudentsResponse = await response.json();
      setStudents(data.data || []);

      // 处理分页信息
      setPagination({
        current: data.pagination?.current || 1,
        pageSize: data.pagination?.pageSize || 10,
        total: data.pagination?.total || 0,
        totalPages: data.pagination?.totalPages || 0
      });
    } catch (error) {
      console.error('加载学生数据失败:', error);
      setError(`加载学生数据失败: ${error instanceof Error ? error.message : '未知错误'}`);
      setStudents([]);
    } finally {
      setIsLoading(false);
    }
  }, [searchFilters]);

  // 从URL读取查询参数并设置筛选条件（仅在组件首次加载或URL参数变化时执行）
  useEffect(() => {
    const classNameParam = searchParams.get('className');
    const collegeParam = searchParams.get('college');
    
    if (classNameParam || collegeParam) {
      setSearchFilters(prev => ({
        ...prev,
        className: classNameParam || '',
        college: collegeParam || ''
      }));
      // 重置分页到第一页
      setPagination(prev => ({
        ...prev,
        current: 1
      }));
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [searchParams]);

  useEffect(() => {
    fetchStudents(pagination.current, pagination.pageSize);
  }, [fetchStudents, pagination.current, pagination.pageSize]);

  // 在 useEffect 里动态处理 indeterminate
  React.useEffect(() => {
    if (selectAllRef.current) {
      selectAllRef.current.indeterminate = selectedIds.length > 0 && selectedIds.length < students.length;
    }
  }, [selectedIds, students]);

  // 获取阶段选项
  const fetchAvailableStages = async () => {
    try {
      const response = await fetch(`${API_BASE}/students/comments/stages`);
      const data = await response.json();
      if (data && data.length > 0) {
        setAvailableStages(data);
      } else {
        // 如果没有数据，设置默认阶段选项
        setDefaultAvailableStages();
      }
    } catch (error) {
      console.error('获取阶段选项失败:', error);
      // 设置默认阶段选项
      setDefaultAvailableStages();
    }
  };

  // 设置默认阶段选项的辅助函数
  const setDefaultAvailableStages = () => {
    setAvailableStages([
      '专业一', '专业二', '专业三', '专业四', '专业五',
      '专高一', '专高二', '专高三', '专高四', '专高五', '专高六'
    ]);
  };

  // 获取学生评语
  const fetchStudentComments = async (studentId: number) => {
    try {
      const response = await fetch(`${API_BASE}/students/${studentId}/comments`);
      if (!response.ok) {
        // 如果返回404或其他错误，直接使用空评语数据
        throw new Error(t('getCommentFailed'));
      }
      const data = await response.json();
      setStudentComments(data);
    } catch (error) {
      console.error('获取学生评语失败:', error);
      // 创建空的评语数据结构
      setStudentComments({
        studentId,
        studentNumber: selectedStudent?.studentId || '',
        studentName: selectedStudent?.name || '',
        className: selectedStudent?.className || '',
        comments: []
      });
    }
  };

  // 保存评语
  const handleSaveComment = async (commentData: Omit<StudentComment, 'date'>) => {
    if (!selectedStudent) return;

    try {
      const response = await fetch(`${API_BASE}/students/${selectedStudent.id}/comments`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(commentData)
      });

      if (!response.ok) {
        throw new Error(t('saveCommentFailed'));
      }

      // 保存成功后重新获取评语数据
      await fetchStudentComments(selectedStudent.id);
    } catch (error) {
      console.error('保存评语失败:', error);
      alert(t('saveCommentFailed'));
    }
  };

  // 删除评语
  const handleDeleteComment = async (stage: string) => {
    if (!selectedStudent) return;

    if (window.confirm(t('confirmDeleteComment', { stage }))) {
      try {
        const response = await fetch(`${API_BASE}/students/${selectedStudent.id}/comments/${stage}`, {
          method: 'DELETE'
        });

        if (!response.ok) {
          // 尝试解析错误响应
          const errorData = await response.json().catch(() => ({}));
          const errorMessage = errorData.error || errorData.data?.error || t('deleteCommentFailed');
          throw new Error(errorMessage);
        }

        // 删除成功后重新获取评语数据
        await fetchStudentComments(selectedStudent.id);
      } catch (error) {
        console.error('删除评语失败:', error);
        alert(`${t('deleteCommentFailed')}: ${error instanceof Error ? error.message : t('retry')}`);
      }
    }
  };

  // 查看评语
  const handleViewComments = async (student: Student) => {
    setSelectedStudent(student);
    setIsCommentModalOpen(true);
    await fetchStudentComments(student.id);
  };

  // 处理分页变化
  const handlePageChange = (page: number, pageSize: number) => {
    setPagination(prev => ({ ...prev, current: page, pageSize }));
    fetchStudents(page, pageSize);
  };

  // 搜索处理函数
  const handleSearchChange = (field: string, value: string) => {
    setSearchFilters(prev => ({
      ...prev,
      [field]: value
    }));
    setPagination(prev => ({ ...prev, current: 1 })); // 重置到第一页
  };




  // 导出学生数据
  const handleExport = async (format: 'csv' | 'excel' = 'excel') => {
    try {
      const token = localStorage.getItem('accessToken') || localStorage.getItem('token');
      const params = new URLSearchParams({ format });

      const headers: Record<string, string> = {};
      if (token) {
        headers['Authorization'] = `Bearer ${token}`;
      }

      const response = await fetch(`${API_BASE}/students/export?${params.toString()}`, {
        headers
      });
      if (!response.ok) {
        throw new Error(t('exportFailed'));
      }
      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `students_export.${format === 'excel' ? 'xlsx' : 'csv'}`;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    } catch (error) {
      console.error('导出失败:', error);
      alert(t('exportFailed'));
    }
  };


  // 添加学生
  const handleAdd = () => {
    setEditingStudent(null);
    setIsModalOpen(true);
  };

  // 编辑学生
  const handleEdit = (student: Student) => {
    setEditingStudent(student);
    setIsModalOpen(true);
  };
  // 保存学生（新增或编辑）
  const handleSave = async (data: Partial<Student>) => {
    try {
      const token = localStorage.getItem('accessToken') || localStorage.getItem('token');
      const isEdit = !!editingStudent?.id;
      const url = isEdit
        ? `${API_BASE}/students/${editingStudent!.id}`
        : `${API_BASE}/students`;
      const method = isEdit ? 'PUT' : 'POST';

      const headers: Record<string, string> = {
        'Content-Type': 'application/json'
      };
      if (token) {
        headers['Authorization'] = `Bearer ${token}`;
      }

      const response = await fetch(url, {
        method,
        headers,
        body: JSON.stringify(data)
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        const errorMessage = errorData.error || errorData.message || t('saveFailed');
        throw new Error(errorMessage);
      }

      setIsModalOpen(false);
      setEditingStudent(null);
      await fetchStudents(pagination.current, pagination.pageSize);
    } catch (error) {
      console.error('保存学生失败:', error);
      alert(`${t('saveFailed')}：${error instanceof Error ? error.message : t('retry')}`);
    }
  };
  // 删除学生
  const handleDelete = async (id: number) => {
    if (window.confirm(t('confirmDelete'))) {
      try {
        const token = localStorage.getItem('accessToken') || localStorage.getItem('token');
        const headers: Record<string, string> = {};
        if (token) {
          headers['Authorization'] = `Bearer ${token}`;
        }

        const response = await fetch(`${API_BASE}/students/${id}`, {
          method: 'DELETE',
          headers
        });

        if (response.ok) {
          fetchStudents(pagination.current, pagination.pageSize);
        } else {
          const errorData = await response.json().catch(() => ({}));
          // 处理不同的错误数据格式
          const errorMessage = errorData.error || errorData.data?.error || t('deleteFailed');
          alert(`${t('deleteFailed')}: ${errorMessage}`);
        }
      } catch (error) {
        console.error('删除失败:', error);
        alert(t('deleteFailedNetwork'));
      }
    }
  };

  // 批量删除选中的学生
  const handleBatchDelete = async () => {
    if (selectedIds.length === 0) return;
    if (!window.confirm(t('confirmBatchDelete', { count: selectedIds.length }))) return;
    try {
      const token = localStorage.getItem('accessToken') || localStorage.getItem('token');
      const headers: Record<string, string> = {};
      if (token) {
        headers['Authorization'] = `Bearer ${token}`;
      }

      for (const id of selectedIds) {
        const response = await fetch(`${API_BASE}/students/${id}`, {
          method: 'DELETE',
          headers
        });
        if (!response.ok) {
          throw new Error(`删除学生 ${id} 失败`);
        }
      }
      setSelectedIds([]);
      await fetchStudents(pagination.current, pagination.pageSize);
    } catch (e) {
      alert(t('batchDeleteFailed'));
    }
  };

  // 处理文件导入
  const handleImport = async (file: File) => {
    setIsImporting(true);
    setImportResult(null);

    const formData = new FormData();
    formData.append('file', file);

    try {
      const response = await fetch(`${API_BASE}/students/import`, {
        method: 'POST',
        body: formData,
      });

      // 检查响应状态
      if (!response.ok) {
        const errorText = await response.text();
        let errorMessage = t('importFailed');

        try {
          const errorJson = JSON.parse(errorText);
          errorMessage = errorJson.error || errorJson.message || errorMessage;
        } catch {
          errorMessage = `HTTP ${response.status}: ${errorText.substring(0, 100)}`;
        }

        setImportResult({
          success: false,
          message: errorMessage,
          total: 0,
          successCount: 0,
          failedCount: 0,
          details: []
        });
        return;
      }

      const result = await response.json();

      if (result.success) {
        setImportResult(result);
        await fetchStudents(pagination.current, pagination.pageSize);
      } else {
        setImportResult({
          success: false,
          message: result.error || result.message || t('importFailed'),
          total: result.total || 0,
          successCount: result.successCount || 0,
          failedCount: result.failedCount || 0,
          details: result.details || []
        });
      }
    } catch (error) {
      console.error('导入失败:', error);
      setImportResult({
        success: false,
        message: error instanceof Error ? error.message : t('importFailed'),
        total: 0,
        successCount: 0,
        failedCount: 0,
        details: []
      });
    } finally {
      setIsImporting(false);
    }
  };

  // 下载导入模板
  const handleDownloadTemplate = async (format: 'csv' | 'excel' = 'csv') => {
    try {
      const response = await fetch(`${API_BASE}/students/import/template?format=${format}`);
      if (!response.ok) {
        throw new Error('下载失败');
      }
      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `student_import_template.${format === 'excel' ? 'xlsx' : 'csv'}`;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    } catch (error) {
      console.error('下载模板失败:', error);
      alert(t('exportFailed'));
    }
  };

  // 初始化阶段选项
  useEffect(() => {
    fetchAvailableStages();
  }, []);
  return (
    <div className={styles.studentManagement}>
      <div className={styles.pageHeader}>
        <h2>{t('title')}</h2>
        <div className={styles.headerActions}>
          {hasPermission('student:import') && (
            <button className={styles.btnSecondary} onClick={() => setIsImportModalOpen(true)}>
              {t('importStudent')}
            </button>
          )}
          {hasPermission('student:export') && (
            <button className={styles.btnSecondary} onClick={() => handleExport('excel')}>
              {t('exportExcel')}
            </button>
          )}
          {hasPermission('student:export') && (
            <button className={styles.btnSecondary} onClick={() => handleExport('csv')}>
              {t('exportCSV')}
            </button>
          )}
          {hasPermission('student:create') && (
            <button className={styles.btnPrimary} onClick={handleAdd}>
              {t('addStudent')}
            </button>
          )}
          {hasPermission('student:delete') && selectedIds.length > 0 && (
            <button className={styles.btnDanger}
              onClick={handleBatchDelete}
            >
              {t('batchDelete', { count: selectedIds.length })}
            </button>
          )}
        </div>
      </div>

      {/* 错误提示 */}
      {error && (
        <div className={styles.errorMessage}>
          <span>{error}</span>
          <button onClick={() => fetchStudents(pagination.current, pagination.pageSize)}>{t('retry')}</button>
        </div>
      )}

      {/* 加载状态 */}
      {isLoading && (
        <div className={styles.loadingState}>{t('common:loading')}</div>
      )}

      {/* 搜索区域 */}
      <div className={styles.searchSection}>
        <div className={styles.searchTitle}>{t('searchTitle')}</div>

        {/* 第一行：学院、班级、姓名、身份证号 */}
        <div className={styles.searchRow}>
          <div className={styles.searchGroup}>
            <label>{t('college')}</label>
            <input
              type="text"
              placeholder={t('pleaseInputCollege')}
              value={searchFilters.college}
              onChange={(e) => handleSearchChange('college', e.target.value)}
            />
          </div>
          <div className={styles.searchGroup}>
            <label>{t('className')}</label>
            <input
              type="text"
              placeholder={t('pleaseInputClassName')}
              value={searchFilters.className}
              onChange={(e) => handleSearchChange('className', e.target.value)}
            />
          </div>
          <div className={styles.searchGroup}>
            <label>{t('name')}</label>
            <input
              type="text"
              placeholder={t('pleaseInputName')}
              value={searchFilters.name}
              onChange={(e) => handleSearchChange('name', e.target.value)}
            />
          </div>
          <div className={styles.searchGroup}>
            <label>{t('idCard')}</label>
            <input
              type="text"
              placeholder={t('pleaseInputIdCard')}
              value={searchFilters.idCard}
              onChange={(e) => {
                const value = e.target.value.replace(/[^\dXx]/g, ''); // 只允许数字和Xx
                if (value.length <= 18) {
                  handleSearchChange('idCard', value);
                }
              }}
              maxLength={18}
            />
          </div>
        </div>

        {/* 第二行：性别、学生状态、手机号、宿舍楼、宿舍号 */}
        <div className={styles.searchRow}>
          <div className={styles.searchGroup}>
            <label>{t('gender')}</label>
            <select
              value={searchFilters.gender}
              onChange={(e) => handleSearchChange('gender', e.target.value)}
            >
              <option value="">{t('pleaseSelectGender')}</option>
              <option value="男">{t('male')}</option>
              <option value="女">{t('female')}</option>
            </select>
          </div>
          <div className={styles.searchGroup}>
            <label>{t('status')}</label>
            <select
              value={searchFilters.status}
              onChange={(e) => handleSearchChange('status', e.target.value)}
            >
              <option value="">{t('pleaseSelectStatus')}</option>
              <option value="active">{t('active')}</option>
              <option value="suspended">{t('onLeave')}</option>
              <option value="graduated">{t('graduated')}</option>
            </select>
          </div>
          <div className={styles.searchGroup}>
            <label>{t('phone')}</label>
            <input
              type="tel"
              placeholder={t('pleaseInputPhone')}
              value={searchFilters.phone}
              onChange={(e) => {
                const value = e.target.value.replace(/\D/g, ''); // 只允许数字
                if (value.length <= 11) {
                  handleSearchChange('phone', value);
                }
              }}
              maxLength={11}
            />
          </div>
          <div className={styles.searchGroup}>
            <label>{t('dormBuilding')}</label>
            <select
              value={searchFilters.dormBuilding}
              onChange={(e) => handleSearchChange('dormBuilding', e.target.value)}
            >
              <option value="">{t('pleaseSelectDormBuilding')}</option>
              <option value="1号楼">1号楼</option>
              <option value="2号楼">2号楼</option>
              <option value="3号楼">3号楼</option>
            </select>
          </div>
          <div className={styles.searchGroup}>
            <label>{t('dormRoom')}</label>
            <select
              value={searchFilters.dormRoom}
              onChange={(e) => handleSearchChange('dormRoom', e.target.value)}
            >
              <option value="">{t('pleaseSelectDormRoom')}</option>
              <option value="101">101</option>
              <option value="102">102</option>
              <option value="201">201</option>
              <option value="202">202</option>
            </select>
          </div>
        </div>

      </div>

      <div className={styles.studentTableContainer}>
        <div className={styles.studentTable}>
          <table>
            <thead>
              <tr>
                <th>
                  <input
                    type="checkbox"
                    ref={selectAllRef}
                    checked={students.length > 0 && selectedIds.length === students.length}
                    onChange={(e) => {
                      if (e.target.checked) {
                        setSelectedIds(students.map(s => s.id));
                      } else {
                        setSelectedIds([]);
                      }
                    }}
                  />
                </th>
                <th>{t('studentId')}</th>
                <th>{t('name')}</th>
                <th>{t('gender')}</th>
                <th>{t('birthDate')}</th>
                <th>{t('idCard')}</th>
                <th>{t('marketingDepartment')}</th>
                <th>{t('className')}</th>
                <th>{t('college')}</th>
                <th>{t('phone')}</th>
                <th>{t('dormBuilding')}</th>
                <th>{t('dormRoom')}</th>
                <th>{t('status')}</th>
                <th>{t('action')}</th>
              </tr>
            </thead>
            <tbody>
              {!students || students.length === 0 ? (
                <tr>
                  <td colSpan={13}>
                    <div className={styles.emptyState}>
                      <div className={styles.icon}>🎓</div>
                      <h3>{t('noData')}</h3>
                      <p>{t('noDataDesc')}</p>
                    </div>
                  </td>
                </tr>
              ) : (
                students.map(student => (
                  <tr key={student.id}>
                    <td>
                      <input
                        type="checkbox"
                        checked={selectedIds.includes(student.id)}
                        onChange={e => {
                          if (e.target.checked) {
                            setSelectedIds(prev => [...prev, student.id]);
                          } else {
                            setSelectedIds(prev => prev.filter(id => id !== student.id));
                          }
                        }}
                      />
                    </td>
                    <td className={styles.studentId}>{student.studentId}</td>
                    <td className={styles.nameCell}>{student.name}</td>
                    <td>{translateDataField(student.gender, 'gender', t, 'student')}</td>
                    <td>{student.birthDate}</td>
                    <td className={styles.idCardCell}>{student.idCard}</td>
                    <td>{student.marketingDepartment}</td>
                    <td>{student.className}</td>
                    <td>{student.college}</td>
                    <td>{student.phone}</td>
                    <td>{student.dormBuilding}</td>
                    <td>{student.dormRoom}</td>
                    <td>
                      <span className={`${styles.status} ${student.status === 'active' ? styles.statusActive :
                        student.status === 'suspended' ? styles.statusSuspended :
                          styles.statusGraduated
                        }`}>
                        {student.status === 'active' ? t('common:activated') :
                          student.status === 'suspended' ? t('common:suspended') : t('common:graduated')}
                      </span>
                    </td>
                    <td>
                      <div className={styles.actionButtons}>
                        {hasPermission('student:update') && (
                          <button
                            className={styles.btnEdit}
                            onClick={() => handleEdit(student)}
                          >
                            {t('edit')}
                          </button>
                        )}
                        <button
                          className={styles.btnComment}
                          onClick={() => handleViewComments(student)}
                        >
                          {t('comment')}
                        </button>
                        {hasPermission('student:delete') && (
                          <button
                            className={styles.btnDelete}
                            onClick={() => handleDelete(student.id)}
                          >
                            {t('delete')}
                          </button>
                        )}
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>

        {/* 分页组件 */}
        {pagination.total > 0 && (
          <div className={styles.pagination}>
            <div className={styles.paginationInfo}>
              {t('totalRecords', { total: pagination.total, current: pagination.current, totalPages: pagination.totalPages })}
            </div>
            <div className={styles.paginationControls}>
              <button
                disabled={pagination.current === 1}
                onClick={() => handlePageChange(pagination.current - 1, pagination.pageSize)}
              >
                {t('previousPage')}
              </button>
              {Array.from({ length: Math.min(5, pagination.totalPages) }, (_, i) => {
                const pageNum = i + 1;
                return (
                  <button
                    key={pageNum}
                    className={pagination.current === pageNum ? styles.active : ''}
                    onClick={() => handlePageChange(pageNum, pagination.pageSize)}
                  >
                    {pageNum}
                  </button>
                );
              })}
              <button
                disabled={pagination.current === pagination.totalPages}
                onClick={() => handlePageChange(pagination.current + 1, pagination.pageSize)}
              >
                {t('nextPage')}
              </button>
            </div>
            <div className={styles.pageSizeSelector}>
              <select
                value={pagination.pageSize}
                onChange={(e) => handlePageChange(1, parseInt(e.target.value))}
              >
                <option value={10}>10 {t('perPage')}</option>
                <option value={20}>20 {t('perPage')}</option>
                <option value={50}>50 {t('perPage')}</option>
                <option value={100}>100 {t('perPage')}</option>
              </select>
            </div>
          </div>
        )}
      </div>

      {/* 添加/编辑学生模态框 */}
      {isModalOpen && (
        <StudentModal
          student={editingStudent}
          onSave={handleSave}
          onClose={() => {
            setIsModalOpen(false);
            setEditingStudent(null);
          }}
        />
      )}

      {isImportModalOpen && (
        <ImportModal
          onImport={handleImport}
          onDownloadTemplate={handleDownloadTemplate}
          onClose={() => {
            setIsImportModalOpen(false);
            setImportResult(null);
          }}
          importResult={importResult}
          isImporting={isImporting}
        />
      )}

      {isCommentModalOpen && (
        <CommentModal
          student={selectedStudent}
          comments={studentComments}
          availableStages={availableStages}
          onSave={handleSaveComment}
          onDelete={handleDeleteComment}
          onClose={() => {
            setIsCommentModalOpen(false);
            setSelectedStudent(null);
            setStudentComments(null);
          }}
        />
      )}
    </div>
  );
};

// 导入模态框组件
interface ImportModalProps {
  onImport: (file: File) => void;
  onDownloadTemplate: (format: 'csv' | 'excel') => void;
  onClose: () => void;
  importResult: ImportResult | null;
  isImporting: boolean;
}

const ImportModal = ({
  onImport,
  onDownloadTemplate,
  onClose,
  importResult,
  isImporting
}: ImportModalProps) => {
  const { t } = useTranslation('student');
  const [file, setFile] = useState<File | null>(null);

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      setFile(e.target.files[0]);
    }
  };

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    if (file) {
      onImport(file);
    }
  };


  return (
    <div className={styles.modalOverlay}>
      <div className={`${styles.modal} ${styles.importModal}`}>
        <div className={styles.modalHeader}>
          <h3>{t('importStudent')}</h3>
          <button className={styles.closeBtn} onClick={onClose}>×</button>
        </div>

        <div className={styles.importInstructions}>
          <h4>{t('importInstructions')}</h4>
          <ul>
            <li>{t('supportedFormats')}</li>
            <li>{t('maxFileSize')}</li>
            <li><strong>{t('requiredFields')}</strong></li>
            <li>{t('studentIdUnique')}</li>
            <li>{t('statusValues')}</li>
            <li>{t('genderValues')}</li>
          </ul>
          <button
            type="button"
            className={styles.btnLink}
            onClick={() => onDownloadTemplate('csv')}
          >
            {t('downloadTemplate')}
          </button>
        </div>

        <div className={styles.templateFormat}>
          <span>{t('templateFormat')}</span>
          <button
            type="button"
            className={styles.btnLink}
            onClick={() => onDownloadTemplate('csv')}
          >
            CSV
          </button>
          <span> | </span>
          <button
            type="button"
            className={styles.btnLink}
            onClick={() => onDownloadTemplate('excel')}
          >
            Excel
          </button>
        </div>

        <form onSubmit={handleSubmit}>
          <div className={styles.formGroup}>
            <label>{t('selectFile')}</label>
            <input
              type="file"
              accept=".csv,.xlsx,.xls"
              onChange={handleFileChange}
              disabled={isImporting}
            />
            {file && (
              <div className={styles.fileInfo}>
                {t('fileSelected', { fileName: file.name })}
              </div>
            )}
          </div>

          {importResult && (
            <div className={`${styles.importResult} ${importResult.success ? styles.success : styles.error}`}>
              <h4>{t('importResult')}</h4>
              <p>{importResult.message}</p>
              {importResult.details && importResult.details.length > 0 && (
                <div className={styles.importDetails}>
                  <h5>{t('detailResults')}</h5>
                  {importResult.details.map((detail, index) => (
                    <div key={index} className={`${styles.detailItem} ${detail.status === 'success' ? styles.success : styles.failed}`}>
                      <span>{detail.name} ({detail.studentId})</span>
                      <span>{detail.message}</span>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

          <div className={styles.modalActions}>
            <button type="button" onClick={onClose} disabled={isImporting}>
              {t('common:cancel')}
            </button>
            <button
              type="submit"
              className={styles.btnPrimary}
              disabled={!file || isImporting}
            >
              {isImporting ? t('importing') : t('startImport')}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

// 评语模态框组件
interface CommentModalProps {
  student: Student | null;
  comments: StudentCommentsData | null;
  availableStages: string[];
  onSave: (data: Omit<StudentComment, 'date'>) => void;
  onDelete: (stage: string) => void;
  onClose: () => void;
}

const CommentModal = ({
  student,
  comments,
  availableStages,
  onSave,
  onDelete,
  onClose
}: CommentModalProps) => {
  const { t } = useTranslation('student');
  const [isAdding, setIsAdding] = useState(false);
  const [formData, setFormData] = useState({
    stage: '',
    teacher: '',
    score: 0,
    comment: ''
  });

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    if (!formData.stage || !formData.teacher || !formData.comment) {
      alert(t('pleaseFillRequired'));
      return;
    }
    onSave(formData);
    setIsAdding(false);
    setFormData({ stage: '', teacher: '', score: 0, comment: '' });
  };

  const usedStages = comments?.comments.map(c => c.stage) || [];
  const availableStagesOptions = availableStages.filter(stage => !usedStages.includes(stage));

  return (
    <div className={styles.modalOverlay}>
      <div className={`${styles.modal} ${styles.largeModal}`}>
        <div className={styles.modalHeader}>
          <h3>{t('commentTitle')} - {student?.name} ({student?.studentId})</h3>
          <button className={styles.closeBtn} onClick={onClose}>×</button>
        </div>

        <div className={styles.studentInfoSection}>
          <h4>{t('basicInfo')}</h4>
          <div className={styles.infoGrid}>
            <div className={styles.infoItem}>
              <label>{t('name')}:</label>
              <span>{student?.name}</span>
            </div>
            <div className={styles.infoItem}>
              <label>{t('studentId')}:</label>
              <span>{student?.studentId}</span>
            </div>
            <div className={styles.infoItem}>
              <label>{t('className')}:</label>
              <span>{student?.className}</span>
            </div>
            <div className={styles.infoItem}>
              <label>{t('college')}:</label>
              <span>{student?.college}</span>
            </div>
            <div className={styles.infoItem}>
              <label>{t('marketingDepartment')}:</label>
              <span>{student?.marketingDepartment}</span>
            </div>
            <div className={styles.infoItem}>
              <label>{t('status')}:</label>
              <span>
                {student?.status === 'active' ? t('active') :
                  student?.status === 'suspended' ? t('onLeave') : t('graduated')}
              </span>
            </div>
          </div>
        </div>

        <div className={styles.commentsSection}>
          <div className={styles.sectionHeader}>
            <h4>{t('stageComment')}</h4>
            {availableStagesOptions.length > 0 && (
              <button
                className={styles.btnPrimary}
                onClick={() => setIsAdding(true)}
              >
                {t('addComment')}
              </button>
            )}
          </div>

          {isAdding && (
            <form onSubmit={handleSubmit} className={styles.commentForm}>
              <div className={styles.formRow}>
                <div className={styles.formGroup}>
                  <label>{t('stage')} *</label>
                  <select
                    value={formData.stage}
                    onChange={(e) => setFormData({ ...formData, stage: e.target.value })}
                    required
                  >
                    <option value="">{t('pleaseSelectStage')}</option>
                    {availableStagesOptions.map(stage => (
                      <option key={stage} value={stage}>{stage}</option>
                    ))}
                  </select>
                </div>
                <div className={styles.formGroup}>
                  <label>{t('teacher')} *</label>
                  <input
                    type="text"
                    value={formData.teacher}
                    onChange={(e) => setFormData({ ...formData, teacher: e.target.value })}
                    placeholder={t('pleaseInputTeacher')}
                    required
                  />
                </div>
                <div className={styles.formGroup}>
                  <label>{t('score')}</label>
                  <input
                    type="number"
                    min="0"
                    max="100"
                    value={formData.score}
                    onChange={(e) => setFormData({ ...formData, score: parseInt(e.target.value) || 0 })}
                    placeholder={t('pleaseInputScore')}
                  />
                </div>
              </div>
              <div className={`${styles.formGroup} ${styles.fullWidth}`}>
                <label>{t('commentTitle')} *</label>
                <textarea
                  value={formData.comment}
                  onChange={(e) => setFormData({ ...formData, comment: e.target.value })}
                  placeholder={t('pleaseInputComment')}
                  rows={3}
                  required
                />
              </div>
              <div className={styles.formActions}>
                <button type="button" onClick={() => {
                  setIsAdding(false);
                  setFormData({ stage: '', teacher: '', score: 0, comment: '' });
                }}>
                  {t('common:cancel')}
                </button>
                <button type="submit" className={styles.btnPrimary}>
                  {t('common:save')}
                </button>
              </div>
            </form>
          )}

          <div className={styles.commentsList}>
            {comments?.comments && comments.comments.length > 0 ? (
              comments.comments.map((comment, index) => (
                <div key={index} className={styles.commentItem}>
                  <div className={styles.commentHeader}>
                    <div className={styles.commentStage}>{comment.stage}</div>
                    <div className={styles.commentMeta}>
                      <span>{t('teacherLabel')} {comment.teacher}</span>
                      <span>{t('scoreLabel')} {comment.score} {t('common:points')}</span>
                      <span>{t('dateLabel')} {comment.date}</span>
                    </div>
                    <button
                      className={styles.btnDeleteSmall}
                      onClick={() => onDelete(comment.stage)}
                    >
                      {t('delete')}
                    </button>
                  </div>
                  <div className={styles.commentContent}>
                    {comment.comment}
                  </div>
                </div>
              ))
            ) : (
              <div className={styles.emptyComments}>
                {t('noComments')}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};
export default StudentManagement;
